package com.momo.todo.activity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.momo.todo.R;
import com.momo.todo.adapter.HistoryListAdapter;
import com.momo.todo.adapter.MyPagerAdapter;
import com.momo.todo.adapter.PlanListAdapter;
import com.momo.todo.config.SqliteConfig;
import com.momo.todo.model.HistoryModel;
import com.momo.todo.model.PlanModel;
import com.momo.todo.utils.LogUtils;
import com.momo.todo.utils.SharedPreferencesUtils;
import com.momo.todo.utils.SqlUtils;
import com.momo.todo.utils.TimeUtils;
import com.momo.todo.view.CustomedDialog;
import com.momo.todo.view.InfoDialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    public static final int REQUEST_CODE_ADD_PLAN = 1001;
    public static final int REQUEST_CPDE_EDIT_PLAN = 1002;

    //滑动布局
    private ViewPager viewPager;
    //计划列表listview
    private ListView lv_plan_list;
    //滑动的两个标签
    private TextView tv_plan, tv_history;
    private TextView tv_nick_name;
    //滑动的两个view
    private View viewPlan, viewHistory;
    //滑动的两个view列表
    private List<View> viewList;
    //显示当前的图片光标
    private ImageView cursor;

    private ListView lv_history_list;
    private ArrayList<HistoryModel> historyList;
    private ImageButton ib_add_plan;

    //计划列表
    private ArrayList<PlanModel> planList;

    private PlanListAdapter planListAdapter;
    private HistoryListAdapter historyListAdapter;

    //指示当前位置的光标图片宽度
    private int bmpWidth;
    //光标偏移距离
    private int offset;
    //当前页卡编号
    private int currIndex = 0;

    private SqlUtils utils;
    private PopupWindow pop;
    private int indexLongClicked = 0;
    private int indexClicked = 0;


    private CustomedDialog selfDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViews();

        initCursor();
        initViewPager();
        initPlanListView();
        initHistoryListView();

        getSomeData();

//        LogUtils.log("hello world!");

        setListener();
    }


    private void setListener() {
        viewPager.setOnPageChangeListener(new MyOnPageChangeListener());
        tv_plan.setOnClickListener(new MyOnClickListener());
        tv_history.setOnClickListener(new MyOnClickListener());
        ib_add_plan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AddPlanActivity.class);
                intent.putExtra("request", REQUEST_CODE_ADD_PLAN);
                startActivityForResult(intent, REQUEST_CODE_ADD_PLAN);
            }
        });


        lv_plan_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                indexLongClicked = position;
//                Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show();
                boolean isTop = planList.get(indexLongClicked).isTop();
                showPopWindows(view, isTop);
                return true;
            }
        });

        lv_plan_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                indexClicked = position;
                PlanModel plan = planList.get(position);

                Intent intent = new Intent(MainActivity.this, AddPlanActivity.class);
                intent.putExtra("planModel", plan);
                intent.putExtra("request", REQUEST_CPDE_EDIT_PLAN);
                startActivityForResult(intent, REQUEST_CPDE_EDIT_PLAN);
            }
        });

        tv_nick_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selfDialog = new CustomedDialog(MainActivity.this);
                selfDialog.setTitle("修改昵称");
                selfDialog.setYesOnclickListener("确定", new CustomedDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        if (!selfDialog.getMessage().trim().equals("")) {

                            SharedPreferencesUtils.setParam(MainActivity.this, "String", selfDialog.getMessage() + "的备忘录");
                            String nickName = selfDialog.getMessage()+"的备忘录";
                            int index = nickName.lastIndexOf("的");
                            int length = nickName.length();
                            SpannableString nickSpanString = new SpannableString(nickName);
                            AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(35);
                            nickSpanString.setSpan(sizeSpan,index,length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            tv_nick_name.setText(nickSpanString);
                            selfDialog.dismiss();
                        }else{
                            Toast.makeText(MainActivity.this, "昵称不能为空", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                selfDialog.setNoOnclickListener("取消", new CustomedDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        selfDialog.dismiss();
                    }
                });
                selfDialog.show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_ADD_PLAN && resultCode == RESULT_OK) {
            PlanModel plan = (PlanModel) data.getSerializableExtra("planModel");

            int index = getFirstUntopIndex();
            planList.add(index, plan);
            planListAdapter.refresh(planList);

            utils.savePlan(plan);
//
//            for(int i=0;i<planList.size();i++){
//                LogUtils.log(planList.get(i).toString());
//            }
        }
        if (requestCode == REQUEST_CPDE_EDIT_PLAN && resultCode == RESULT_OK) {
            PlanModel plan = (PlanModel) data.getSerializableExtra("planModel");

            PlanModel deletePlan = planList.get(indexClicked);

            planList.set(indexClicked, plan);
            planListAdapter.refresh(planList);

            utils.delete(deletePlan);
            utils.savePlan(plan);

        }
    }

    private int getFirstUntopIndex() {
        for (int i = 0; i < planList.size(); i++) {
            PlanModel model = planList.get(i);
            if (model.isTop() == false) {
                return i;
            }
        }
        return planList.size();
    }

    private void findViews() {

        viewPager = (ViewPager) findViewById(R.id.view_pager);
        tv_history = (TextView) findViewById(R.id.tv_history);
        tv_plan = (TextView) findViewById(R.id.tv_plan);

        utils = new SqlUtils(this, SqliteConfig.DATABASE_NAME);
        tv_nick_name = (TextView) findViewById(R.id.tv_nick_name);
        String nickName = (String) SharedPreferencesUtils.getParam(MainActivity.this, "String", "备忘录");

        int index = nickName.lastIndexOf("备");
        int length = nickName.length();
        if(index != 0) {
            SpannableString nickSpanString = new SpannableString(nickName);
            AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(35);
            nickSpanString.setSpan(sizeSpan, index - 1, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tv_nick_name.setText(nickSpanString);
        }else{
            tv_nick_name.setText("备忘录");
        }


    }

    private void initViewPager() {
        LayoutInflater inflater = getLayoutInflater();
        viewPlan = inflater.inflate(R.layout.layout_page_plan, null);
        viewHistory = inflater.inflate(R.layout.layout_page_history, null);
        viewList = new ArrayList<View>();
        viewList.add(viewPlan);
        viewList.add(viewHistory);
        MyPagerAdapter pagerAdapter = new MyPagerAdapter(viewList);
        viewPager.setAdapter(pagerAdapter);
    }

    private void initCursor() {
        cursor = (ImageView) findViewById(R.id.cursor);
        bmpWidth = BitmapFactory.decodeResource(getResources(), R.drawable.cursor).getWidth();
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        offset = (screenWidth / 2 - bmpWidth) / 2;
        Matrix matrix = new Matrix();
        matrix.postTranslate(offset, 0);
        cursor.setImageMatrix(matrix);
    }

    private void initPlanListView() {
        lv_plan_list = (ListView) viewPlan.findViewById(R.id.lv_plan_list);
        ib_add_plan = (ImageButton) viewPlan.findViewById(R.id.ib_add_plan);

        planList = (ArrayList) utils.getPlanList();
//        LogUtils.log("hello world");
        updatePlanList();

        planListAdapter = new PlanListAdapter(this, planList);
        lv_plan_list.setAdapter(planListAdapter);


    }

    private void showPopWindows(View v, boolean isTop) {
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_pop, null);
        pop = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        pop.setContentView(view);
        pop.setTouchable(true);
        pop.setOutsideTouchable(true);
        pop.setBackgroundDrawable(new ColorDrawable());

        //popupWindows中按钮设置点击事件
        ImageButton ib_top = (ImageButton) view.findViewById(R.id.ib_top);
        ImageButton ib_delete = (ImageButton) view.findViewById(R.id.ib_delete);
        ImageButton ib_finished = (ImageButton) view.findViewById(R.id.ib_finished);
        TextView tv_is_top = (TextView) view.findViewById(R.id.tv_is_top);

        if (isTop) {
            ib_top.setBackgroundResource(R.drawable.style_untop_button);
            tv_is_top.setText("取消置顶");
            tv_is_top.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
        } else {
            ib_top.setBackgroundResource(R.drawable.style_top_plan_button);
            tv_is_top.setText("置顶");
            tv_is_top.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
        }

        ib_delete.setOnClickListener(new MyImageButtonOnClickListener());
        ib_finished.setOnClickListener(new MyImageButtonOnClickListener());
        ib_top.setOnClickListener(new MyImageButtonOnClickListener());

        pop.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int height = pop.getContentView().getMeasuredHeight();
        int width = pop.getContentView().getMeasuredWidth();

        int marginRight = (int) (0.05 * v.getWidth());
        int offsetX = v.getWidth() - width;
        int offsetY = -(v.getHeight());

        int[] location = new int[2];
        v.getLocationOnScreen(location);

//        pop.showAsDropDown(v,offsetX,offsetY);
        View rootView = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);
        pop.showAtLocation(rootView, Gravity.NO_GRAVITY, location[0] + offsetX, location[1] - height);
    }

    private void initHistoryListView() {
        lv_history_list = (ListView) viewHistory.findViewById(R.id.lv_history_list);
//        historyList = new ArrayList<>();
//        HistoryModel history  = new HistoryModel();
//        history.setTime(System.currentTimeMillis());
//        history.setPlanList(planList);
//        historyList.add(history);
//

//        HistoryModel historyModel = new HistoryModel();
//        long finishTime = TimeUtils.convertTimeStamp("2016-11-13 5:06:23");
//        PlanModel plan = new PlanModel();
//        plan.setType(1);
//        plan.setContent("测试测试");
//        plan.setTime(0);
//        utils.saveHistoryItem(finishTime,plan);

        historyList = (ArrayList<HistoryModel>) utils.getHistoryList();
//        LogUtils.logList(historyList);

        updateHistoryList();


        historyListAdapter = new HistoryListAdapter(this, historyList);
        lv_history_list.setAdapter(historyListAdapter);


    }

    public void getSomeData() {

    }

    private class MyImageButtonOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ib_top:
                    if (!planList.get(indexLongClicked).isTop()) {
                        planList.get(indexLongClicked).setTop(true);
                    } else {
                        planList.get(indexLongClicked).setTop(false);
                    }
                    LogUtils.log("time:" + planList.get(indexLongClicked).getTime());
                    utils.update(planList.get(indexLongClicked));
                    updatePlanList();
                    planListAdapter.refresh(planList);

                    pop.dismiss();
                    break;
                case R.id.ib_delete:
                    final InfoDialog deleteDialog = new InfoDialog(MainActivity.this,1);
                    deleteDialog.setTitle("温馨提示");
                    deleteDialog.setMessage("确定要删除计划吗？");
                    deleteDialog.setYesOnclickListener("确定", new CustomedDialog.onYesOnclickListener() {
                        @Override
                        public void onYesClick() {
                            Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
//                            LogUtils.log("time:" + planList.get(indexLongClicked).getTime());
                            utils.delete(planList.get(indexLongClicked));
                            planList.remove(indexLongClicked);

                            planListAdapter.refresh(planList);
                            pop.dismiss();
                            deleteDialog.dismiss();
                        }
                    });
                    deleteDialog.setNoOnclickListener("取消", new CustomedDialog.onNoOnclickListener() {
                        @Override
                        public void onNoClick() {
                            deleteDialog.dismiss();
                        }
                    });
                    deleteDialog.show();
                    break;
                case R.id.ib_finished:

                    final InfoDialog finishDialog = new InfoDialog(MainActivity.this,2);
                    finishDialog.setTitle("温馨提示");
                    finishDialog.setMessage("确定计划已完成吗？");
                    finishDialog.setYesOnclickListener("确定", new CustomedDialog.onYesOnclickListener() {
                        @Override
                        public void onYesClick() {

                            long currTime = System.currentTimeMillis();
                            PlanModel addPlan = planList.get(indexLongClicked);
//                    LogUtils.log(addPlan.toString());

                            if (historyList.size() == 0) {
                                HistoryModel firstItem = new HistoryModel();
                                firstItem.setTime(currTime);
                                firstItem.getPlanList().add(addPlan);
                                historyList.add(0, firstItem);
                            } else {
                                HistoryModel firstItem = historyList.get(0);
                                if (TimeUtils.isSameDay(firstItem.getTime(), currTime)) {
                                    historyList.get(0).getPlanList().add(0, addPlan);
                                } else {
                                    HistoryModel history = new HistoryModel();
                                    history.setTime(currTime);
                                    history.getPlanList().add(addPlan);
                                    historyList.add(0, history);
                                }
                            }
//                    LogUtils.log(historyList.get(0).getPlanList().get(0).toString());

                            historyListAdapter.refresh(historyList);

                            utils.delete(planList.get(indexLongClicked));
                            planList.remove(indexLongClicked);

                            planListAdapter.refresh(planList);

//                    Toast.makeText(MainActivity.this, indexLongClicked+"", Toast.LENGTH_SHORT).show();
                            pop.dismiss();
                            Toast.makeText(MainActivity.this, "已完成", Toast.LENGTH_SHORT).show();

                            utils.saveHistoryItem(currTime, addPlan);



                            finishDialog.dismiss();
                        }
                    });
                    finishDialog.setNoOnclickListener("取消", new CustomedDialog.onNoOnclickListener() {
                        @Override
                        public void onNoClick() {
                            finishDialog.dismiss();
                        }
                    });
                    finishDialog.show();





                    break;
                default:
                    break;
            }
        }
    }

    private void updatePlanList() {
        Comparator<PlanModel> sortByTime = new Comparator<PlanModel>() {
            @Override
            public int compare(PlanModel plan1, PlanModel plan2) {
                long plan1Time = plan1.getTime();
                long plan2Time = plan2.getTime();

                if (plan1Time - plan2Time < 0) {
                    return 1;
                } else if (plan1Time - plan2Time == 0) {
                    return 0;
                } else {
                    return -1;
                }
            }
        };

        Collections.sort(planList, sortByTime);
        ArrayList<PlanModel> copyList = new ArrayList<>();

        for (PlanModel plan : planList) {
            if (plan.isTop()) {
                copyList.add(plan);
            }
        }
        for (PlanModel plan : planList) {
            if (!plan.isTop()) {
                copyList.add(plan);
            }
        }

        planList.clear();
        planList.addAll(copyList);


    }

    private void updateHistoryList() {
        Comparator<HistoryModel> sortByTime = new Comparator<HistoryModel>() {
            @Override
            public int compare(HistoryModel history1, HistoryModel history2) {
                long plan1Time = history1.getTime();
                long plan2Time = history2.getTime();

                if (plan1Time - plan2Time < 0) {
                    return 1;
                } else if (plan1Time - plan2Time == 0) {
                    return 0;
                } else {
                    return -1;
                }
            }
        };

        Collections.sort(historyList, sortByTime);
    }

    private class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        int one = offset * 2 + bmpWidth;

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            Animation animation = new TranslateAnimation(one * currIndex, one * position, 0, 0);
            currIndex = position;
            animation.setFillAfter(true);
            animation.setDuration(200);
            cursor.startAnimation(animation);

//            LogUtils.log("-------planlist----------");
//            for(PlanModel plan:planList){
//                LogUtils.log(plan.toString());
//            }
//            LogUtils.log("-----------------");
//
//            LogUtils.log("--------history_planlist---------");
//            for(PlanModel plan:historyList.get(0).getPlanList()){
//                LogUtils.log(plan.toString());
//            }
//            LogUtils.log("-----------------");
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    private class MyOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_plan:
                    viewPager.setCurrentItem(0);
                    break;
                case R.id.tv_history:
                    viewPager.setCurrentItem(1);
                    break;
                default:
                    break;
            }
        }

    }

    public void sortList(ArrayList<PlanModel> planList) {
        ArrayList<PlanModel> copyList = new ArrayList<>();
        for (PlanModel plan : planList) {
            if (plan.getType() == PlanModel.PLAN_TYPE_STUDY) {
                copyList.add(plan);
            }
        }

        for (PlanModel plan : planList) {
            if (plan.getType() == PlanModel.PLAN_TYPE_LIFE) {
                copyList.add(plan);
            }
        }

        for (PlanModel plan : planList) {
            if (plan.getType() == PlanModel.PLAN_TYPE_OTHER) {
                copyList.add(plan);
            }
        }

        planList.clear();
        planList.addAll(copyList);

    }
}
